package hibernate.fileControler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.primefaces.model.UploadedFile;

public class UploadFiles {
	public static String newFileDirectory = "C:/Users/HAVANE/workspace-indigo/yeniEMMY/WebContent/";
	private boolean islem;
	private String filePath;
	
	public static UploadFiles saveFile(UploadedFile file, String dest) throws Exception {
		try{
			//ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().
			//		getExternalContext().getContext();
			//String newFileName = servletContext.getRealPath("//yazilimlar//" +file.getFileName() );
			
			//String dbPath =CheckFileHash.fileCheck(file)+file.getFileName().toLowerCase();
			String dbPath =CheckFileHash.fileCheck(file)+getFileExtension(file.getFileName());
			
			String fileName = newFileDirectory+dest+"/"+dbPath;
			//if(! ListFiles.checkFile(newFileDirectory+dest, CheckFileHash.fileCheck(file))){    
			//	System.out.println("Hata fırlatır");
	        //}  burası ResimlerBean içirisinde kontrol edilmektedir...
			
			FileOutputStream fos = new FileOutputStream(new File(fileName));
            InputStream is = file.getInputstream();
            
          
            
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];
            int a;
            while(true){
                a = is.read(buffer);
                if(a < 0) break;
                fos.write(buffer, 0, a);
                fos.flush();
            }
            fos.close();
            is.close();
            UploadFiles sonuc = new UploadFiles();
            sonuc.setFilePath(dbPath);
            sonuc.setIslem(true);
            return sonuc;
        }catch(IOException e){
        	System.out.println("Upload Files Error : "+e);
        	throw new MyException("dosya kaydedilemedi.");
        	//UploadFiles sonuc = new UploadFiles();
        	//sonuc.setIslem(false);
            //return sonuc;
        }  
	}
	
	public static String getFileExtension(String flName){
		String fname="";
		String ext="";
		
		int mid= flName.lastIndexOf(".");
		
		fname=flName.substring(0,mid);
		
		ext=flName.substring(mid+1,flName.length());  
		
		System.out.println("File name ="+fname);
		System.out.println("Extension ="+ext);  
		return "."+ext;
	}
	public boolean isIslem() {
		return islem;
	}
	public void setIslem(boolean islem) {
		this.islem = islem;
	}
	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
}